package cn.calm.client;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import cn.calm.commons.entity.Content;


public class MainActivity extends Activity {
	//
	public static final String SERVER_NAME="http://192.168.0.200:8080";
	static{
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
        .detectDiskReads()
        .detectDiskWrites()
        .detectNetwork()   // or .detectAll() for all detectable problems
        .penaltyLog()
        .build());
		StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
		                .detectLeakedSqlLiteObjects()
		                .penaltyLog()
		                .penaltyDeath()
		                .build());
	}
	ListView list;
	private Handler handler;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Toast.makeText(getApplicationContext(),R.string.loading,
				Toast.LENGTH_SHORT).show();
		setContentView(R.layout.activity_main);
		
		list = (ListView) findViewById(R.id.list);
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Content con = (Content) parent.getItemAtPosition(position);
				Intent intent=new Intent();
				intent.putExtra("content", con);
				intent.setClass(MainActivity.this, DetailActivity.class);
				startActivity(intent);
			}
		});
		handler=new Handler();  
		Runnable run=	new Runnable() {
			
			@Override
			public void run() {
				
				byte[] data = NetWorkTools
						.getData(SERVER_NAME+"/server/json!listAll");
				String jsonStr = new String(data);
				List<Content> listData = new ArrayList<Content>();
				try {
					JSONArray array = (JSONArray) new JSONTokener(jsonStr).nextValue();
					int length = array.length();
					JSONObject jsonObject;
					Content con;
					for (int i = 0; i < length; i++) {
						jsonObject = array.getJSONObject(i);
						con = new Content();
						con.setId(jsonObject.getInt("id"));
						con.setName(jsonObject.getString("name"));
						con.setDescription(jsonObject.getString("description"));
						con.setUrl(jsonObject.getString("url"));
						listData.add(con);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				list.setAdapter(new ImageAdapter(listData, MainActivity.this, R.layout.item));
				Toast.makeText(getApplicationContext(),R.string.load_success,
						Toast.LENGTH_SHORT).show();
			}
		};
		handler.post(run);
		
	}
}
